const PageHelper = require('./pageHelper');
const ph = require('./PuppeteerHelper');
const https = require('https');
var pageHelper = new PageHelper();
var productData = require('./productData');
/**
 * 根据商品详情页的url获取商品信息
 * @param {string} url 商品详情页的url 
 * @param {PageHelper} pageHelper pupperter的pageHelper对象
 */
async function fetchByUrl(url, pageHelper) {
  try {
    if (!pageHelper) {
      await ph.init();
      pageHelper = ph;
    }
    pageHelper = new PageHelper(pageHelper.page);
    await pageHelper.page.goto(url,{ waitUntil: 'domcontentloaded' });
    await pageHelper.pageLoadByElement('#nav-description');
    const itemData = await pageHelper.page.evaluate(() => {
      return runParams.data;
    });
    productData.title = itemData?.productInfoComponent?.subject;
    productData.price = itemData?.priceComponent?.discountPrice?.minActivityAmount?.value;
    if (!productData.price) productData.price = itemData?.priceComponent?.origPrice?.minAmount?.value;
    if (!productData.price) productData.price = itemData?.priceComponent?.origPrice?.minPrice;


    productData.imageList = itemData?.imageComponent;
    if (productData.imageList) productData.imageList = getFirstArrayProperty(productData.imageList);
    productData.descriptUrl = itemData?.productDescComponent?.descriptionUrl;
    productData.unitName = itemData?.productInfoComponent?.multiUnitName;
    if (!productData.unitName) productData.unitName = itemData?.productInfoComponent?.oddUnitName;
    if (productData.descriptUrl) {
      const html = await downloadHtml(productData.descriptUrl);
      productData.descriptHtml = html;
    }
    return productData;
  } catch (error) {
    console.log(error);
  }
}
/**
 * 获取对象的第一个数组属性
 */
function getFirstArrayProperty(obj) {
  let firstArray = null;

  for (const key of Object.keys(obj)) {
    const value = obj[key];
    if (Array.isArray(value)) {
      firstArray = value;
      break;
    }
  }
  return firstArray;
}
/**
 * 下载指定url的Html内容
 * @param {string} url 要下载Html内容的url
 */
async function downloadHtml(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (response) => {
      let data = '';

      response.on('data', (chunk) => {
        data += chunk;
      });

      response.on('end', () => {
        resolve(data);
      });
    }).on('error', (error) => {
      reject(error);
    });
  });
}
module.exports = fetchByUrl;
/**
 * 测试用例
 */
// (async () => {
//   const res = await fetchByUrl('https://www.aliexpress.com/item/1005005145939620.html?pdp_ext_f=%7B%22ship_from%22%3A%22CN%22%2C%22sku_id%22%3A%2212000031848325700%22%7D&scm=1007.39065.271082.0&scm_id=1007.39065.271082.0&scm-url=1007.39065.271082.0&pvid=a094e3f3-a5a4-435b-89ce-053700352049&utparam=%257B%2522process_id%2522%253A%2522standard-portal-process-2%2522%252C%2522x_object_type%2522%253A%2522product%2522%252C%2522pvid%2522%253A%2522a094e3f3-a5a4-435b-89ce-053700352049%2522%252C%2522belongs%2522%253A%255B%257B%2522floor_id%2522%253A%252238756579%2522%252C%2522id%2522%253A%252232194405%2522%252C%2522type%2522%253A%2522dataset%2522%257D%252C%257B%2522id_list%2522%253A%255B%255D%252C%2522type%2522%253A%2522gbrain%2522%257D%255D%252C%2522pageSize%2522%253A%252224%2522%252C%2522language%2522%253A%2522en%2522%252C%2522scm%2522%253A%25221007.39065.271082.0%2522%252C%2522countryId%2522%253A%2522US%2522%252C%2522scene%2522%253A%2522TopSelection-Waterfall%2522%252C%2522tpp_buckets%2522%253A%252221669%25230%2523265320%252396_21669%25234190%252319160%2523299_29065%25230%2523271082%25233%2522%252C%2522x_object_id%2522%253A%25223256804959624868%2522%257D&pdp_npi=3%40dis%21USD%21US%20%2450.81%21US%20%2416.31%21%21%21%21%21%402108472f16887516410142614e19c1%2112000031848325700%21gdf%21%21&spm=a2g0o.tm1000002496.5277427660.d0&aecmd=true&gatewayAdapt=4itemAdapt');
//   console.log(res);
// })();
